let db = require( '../db/db.js' );

const tableName = 'core.api_key';


exports.insert = async function ( apikey ) {
    let sql = `INSERT INTO ${ tableName } (user_id, key, trust, type, description, created_by, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, now(), now())`;
    let params = [ apikey.userId, apikey.key, apikey.trust, apikey.type, apikey.description, apikey.createdBy ];

    try {
        let result = await db.runSql( sql, params );
        return result;
    } catch ( e ) {
        console.log( '获取AK出错', e );
    }
}

exports.setTrust = async function ( apikey, trust ) {
    let sql = `update ${ tableName } set trust = $1 where key=$2`;
    let params = [ trust, apikey ];

    try {
        let result = await db.runSql( sql, params );
        return result;
    } catch ( e ) {
        console.log( '更新AK信任域出错', e );
    }
}
exports.remove = async function ( apikey ) {

    let sql = `delete from ${ tableName } where key=$1`;
    let params = [ apikey ];

    try {
        let result = await db.runSql( sql, params );
        return result;
    } catch ( e ) {
        console.log( '删除AK出错', e );
    }

}

exports.getByUser = async function ( userId, orderBy = 'updated_at', sortType = 'desc' ) {
    let sql = `SELECT * FROM ${ tableName } WHERE user_id=$1 order by ${ orderBy } ${ sortType }`;
    let params = [ userId ];
    try {
        let results = await db.runSql( sql, params );
        if ( results ) {
            return results.rows;
        }
        return null;
    } catch ( e ) {
        console.log( '获取AK出错', e );
    }
}